package heven.holt.wan.android.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint
import heven.holt.library.base.BaseFragment
import heven.holt.library.adapter.CommonViewPagerAdapter
import heven.holt.wan.android.databinding.FragmentProjectBinding
import heven.holt.wan.android.viewmodel.ProjectViewModel

@AndroidEntryPoint
class ProjectFragment : BaseFragment<FragmentProjectBinding>() {
    private val projectViewModel: ProjectViewModel by viewModels()

    override fun bindViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): FragmentProjectBinding = FragmentProjectBinding.inflate(inflater, container, false)

    override fun initView() {
    }

    override fun initData() {
        projectViewModel.projectTreeLiveData.observe(viewLifecycleOwner) { projectTree ->
            val fragments = mutableListOf<Fragment>()
            projectTree.forEach { fragments.add(ProjectArticleFragment.newInstance(it.id ?: -1)) }
            binding.viewPager.adapter = CommonViewPagerAdapter(this, fragments)
            TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position ->
                tab.text = projectTree[position].name
            }.attach()
        }

        if (projectViewModel.projectTreeLiveData.value == null) {
            projectViewModel.requestProjectTree()
        }
    }
}